import { invoke } from '@tauri-apps/api/core';

export interface FileInfo {
  path: string;
  name: string;
  extension: string;
  size: number;
  created: string;
  modified: string;
  is_directory: boolean;
}

export interface FileFilter {
  name: string;
  extensions: string[];
}

export class FileService {
  static async selectVideoFile(): Promise<string | null> {
    try {
      const result = await invoke('select_video_file');
      return result as string | null;
    } catch (error) {
      throw new Error(`选择视频文件失败: ${error}`);
    }
  }

  static async selectVideoFiles(): Promise<string[]> {
    try {
      const result = await invoke('select_video_files');
      return result as string[];
    } catch (error) {
      throw new Error(`选择视频文件失败: ${error}`);
    }
  }

  static async selectOutputDirectory(): Promise<string | null> {
    try {
      const result = await invoke('select_output_directory');
      return result as string | null;
    } catch (error) {
      throw new Error(`选择输出目录失败: ${error}`);
    }
  }

  static async createOutputPath(
    inputPath: string,
    outputFormat: string,
    outputDir?: string,
    suffix?: string
  ): Promise<string> {
    try {
      const result = await invoke('create_output_path', {
        inputPath,
        outputFormat,
        outputDir,
        suffix,
      });

      return result as string;
    } catch (error) {
      throw new Error(`创建输出路径失败: ${error}`);
    }
  }

  static async validateVideoFile(filePath: string): Promise<boolean> {
    try {
      const result = await invoke('validate_video_file', {
        filePath,
      });

      return result as boolean;
    } catch (error) {
      return false;
    }
  }

  static async getFileInfo(filePath: string): Promise<FileInfo> {
    try {
      // 这里可以添加自定义的文件信息获取逻辑
      // 目前使用系统文件统计
      const stats = await this.getFileStats(filePath);

      // 使用URL解析路径
      const url = new URL(`file://${filePath}`);
      const fileName = url.pathname.split('/').pop() || '';
      const fileExt = fileName.split('.').pop()?.toLowerCase() || '';

      return {
        path: filePath,
        name: fileName,
        extension: fileExt,
        size: stats.size || 0,
        created: stats.birthtime || new Date().toISOString(),
        modified: stats.mtime || new Date().toISOString(),
        is_directory: stats.isDirectory?.() || false,
      };
    } catch (error) {
      throw new Error(`获取文件信息失败: ${error}`);
    }
  }

  private static async getFileStats(_filePath: string): Promise<any> {
    // 使用 Tauri 的文件系统 API 获取文件状态
    // 这里需要根据实际的文件系统 API 实现
    return {
      size: 0,
      birthtime: new Date().toISOString(),
      mtime: new Date().toISOString(),
      isDirectory: () => false,
    };
  }

  static async fileExists(_filePath: string): Promise<boolean> {
    try {
      // 这里可以实现文件存在性检查
      // 目前使用简单的 Promise 包装
      return new Promise(resolve => {
        // 在实际实现中，应该使用 Tauri 的文件系统 API
        resolve(true);
      });
    } catch (error) {
      return false;
    }
  }

  static async getFileSize(filePath: string): Promise<number> {
    try {
      const info = await this.getFileInfo(filePath);
      return info.size;
    } catch (error) {
      throw new Error(`获取文件大小失败: ${error}`);
    }
  }

  // 工具方法：格式化文件大小
  static formatFileSize(bytes: number): string {
    if (bytes === 0) return '0 B';

    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));

    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  }

  // 工具方法：获取文件扩展名
  static getFileExtension(filePath: string): string {
    const path = require('path');
    return path.extname(filePath).toLowerCase().replace('.', '');
  }

  // 工具方法：获取文件名（不含扩展名）
  static getFileNameWithoutExtension(filePath: string): string {
    const path = require('path');
    return path.basename(filePath, path.extname(filePath));
  }

  // 工具方法：检查是否为视频文件
  static isVideoFile(filePath: string): boolean {
    const videoExtensions = ['mp4', 'avi', 'mov', 'mkv', 'wmv', 'flv', 'webm'];
    const ext = this.getFileExtension(filePath);
    return videoExtensions.includes(ext);
  }

  // 工具方法：检查是否为音频文件
  static isAudioFile(filePath: string): boolean {
    const audioExtensions = ['mp3', 'wav', 'aac', 'flac', 'ogg'];
    const ext = this.getFileExtension(filePath);
    return audioExtensions.includes(ext);
  }
}
